<template>
	<div class="environWrapper">
		<Header>
			<div style="display: flex;justify-content: space-between;width: 100%">
				<div style="color: #333;font-size:20px;font-weight: 600">{{this.expeInfo.ecname}}</div>
				<ul class="operation">
					<li>
						<img src="../../../assets/exper/vm.png" style="width: 18px;height: 18px;vertical-align: middle" alt="vm">
						<span style="width:100px;cursor: pointer">{{this.curVmName}}</span>
					</li>
					<li>
						<Divider type="vertical" />
					</li>
					<!--<li style="width: 120px">
                        <span style="font-size:26px;color:rgb(51, 115, 255);font-weight: 600">
                        <span style="position: relative;top: 2px;">{{curTime.h}}:{{curTime.m}}:{{curTime.s}}</span>
                    </span>
                    </li>-->
				</ul>
			</div>
		</Header>
		<Content>
			<div style="display: flex;justify-content: flex-start;width: 100%;height: 100%">
				<div class="left-wrap">
					<div class="contrlIcon">
						<img :src="contrlImg" style="height: 75px;width: 17px" @click="closeLeft">
					</div>
					<div class="left-menu">
						<div class="left-items">
							<div class="left-item" v-for="(value,index) in leftMenu" :key="index" @click.prevent="clickMenu(index)">
								<div class="item-text" :class="{textActive:value.type}">{{value.name}}</div>
								<div class="item-line" :class="{lineActive:value.type}"></div>
							</div>
						</div>
						<Divider style="height: 100%" type="vertical" />
					</div>
					<div class="left-content" :style="{width:leftContentWidth}">
						<div class="exap-data-wrap" :style="{height:leftDataHei}">
							<div class="exap-data">
								<div class="main_list">
									<div class="exp" data-name="指导书列表" style="display: block;">
										<div class="guidancebook">
											<div v-if="expeInfo.customType==1">
												<guideIframe :mdPath="expeInfo.guide" :guideSrc="guideSrc" :contentHeiNei="leftDataHei" :type="1"></guideIframe>
											</div>
											<div v-else>
												<SectionList :data="guideList" :showQuestion="false"></SectionList>
											<!-- <div class="exptaskdiv">
												<span v-show="!showCloseAndOpenBtn" @click="exptaskexpand">展开</span>
												<span v-show="showCloseAndOpenBtn" @click="exptaskclose">关闭</span>
											</div>
											<div class="guidancebookList">
												<div class="guidancebookdiv" v-for="(value,index) in guideList" :key='index'>
													<div class="guidancebooktitle" :style="{'background-image': `url(${closeSingle})!important`}" @click="guidancebooktitle(index)" data-name="指导书标题">{{value.sectionname}}</div>
													<div class="guidancebookcontent" data-name="指导书内容" style="overflow: hidden; display: block;" v-html="xss(escape2Html(value.sectiontext))"></div>
												</div>
											</div> -->
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div id="content">
					<div id="mainIframe"></div>
				</div>
			</div>
		</Content>
		<Modal v-model="closeWindowModal" width="360">
			<p slot="header" style="color:#f60;text-align:center">
				<Icon type="ios-information-circle-outline"></Icon>
				<span>提示</span>
			</p>
			<div style="text-align:center;color:#f60;">
				<h4 v-if="!teacherId">课件环境即将销毁</h4>
				<h4 v-if="teacherId">没有获取到投屏信息</h4>
				<h4 v-if="!teacherId">页面将于<span style="font-size:20px;">{{this.closeTime}}</span>秒后关闭</h4>
				<h4 v-if="teacherId">页面即将关闭</h4>
			</div>
			<div slot="footer"></div>
		</Modal>
	</div>
</template>

<script>
  import {mapState} from "vuex";
	import $ from 'jquery'
	import encryption from '@/libs/encryption.js'
	import Guacamole from './all.min'
	import { escape2Html } from '@/libs/utils'
	
	//接口
	import {
		experimentDetail
	} from '@/api/selfStudy/courseExp.js'
	import {
		sectionList_new
	} from '@/api/guide.js'
	import {
		getRecord
	} from '@/api/selfStudy/access.js'
	import guideIframe from '@/view/experimentalScene/designPanel/guideIframe.vue'
	import SectionList from '@/components/common/guide-section-list'
	export default {
		data() {
				return {
					fullWidth: document.documentElement.clientWidth,
					fullHeight: document.documentElement.clientHeight,
					USER_ID: '',
					teacherId: '',
					// 本地取数据
					proId: '',
					ecId: '',
					expeInfo: {},
					// 倒计时
					leftTime: 0,
					curTime: {
						h: '04',
						m: '00',
						s: '00'
					},
					vmList: [],
					// 关闭页面
					closeWindowModal: false,
					closeTime: 5, // 关闭页面倒计时
					// 连接
					curVmName: '',
					curAccess: '',
					// 左侧抽屉
					leftMenu: [{
							name: '指导书',
							type: true,
						},
						//                    {
						//                        name:'问答',
						//                        type:false,
						//                    },
						//                    {
						//                        name:'笔记',
						//                        type:false,
						//                    },
						//                    {
						//                        name:'习题',
						//                        type:false,
						//                    }
					],
					leftContentWidth: '650px',
					contrlImg: require('../../../assets/exper/close-book.png'),
					contrlStatus: true,
					// 说明指导书信息
					guideList: [],
					leftDataHei: 'auto',
					// 指导书展开收缩按钮的显示
					showCloseAndOpenBtn: true,
					connRecordList: []
				}
			},
			components:{guideIframe,SectionList},
			mounted() {
				// 试验机宽度
				this.getVmsWidth()
				this.leftDataHei = this.fullHeight - 128 + 'px'
				$('.ivu-divider-vertical').css('margin', '0px')
					//          this.getVmList()
				this.getExperData()
					//          this.getDestoryTime()
					//          this.destoryInterval = setInterval(() => {
					//              this.getDestoryTime();
					//          },1000*60*10)
				this.getRecordList({
					projectId: this.proId,
					userId: this.teacherId,
					status: 'connected'
				});
				setInterval(() => {
					this.getRecordList({
						projectId: this.proId,
						userId: this.teacherId,
						status: 'connected'
					});
				}, 10000)
				//          window.onbeforeunload = ()=>{
				//          	if(this.curVmName){
				//          		this.modifyCheckScreenStatus(0);
				//          	}
				//          }
			},
			created() {
				// 获取用户id
				let October = sessionStorage.getItem('November')
				October = JSON.parse(encryption.SelfUseDecrypt(October))
				this.USER_ID = October.userId
					//this.getToken = cookieUse.getCookie('desig-token') || ''
					// 工程id  课件id 用户id
				this.proId = this.$route.query.prjId
				this.ecId = this.$route.query.ecId
				this.teacherId = this.$route.query.userId
			},
			updated() {
			},
			beforeDestory() {
				clearTimeout(this.timeout);
				clearInterval(this.destoryInterval);
			},
			computed: {
				//          ...mapGetters('edu',[
				//              'connRecordList'
				//          ])
				...mapState('style', {
					openSingle: ({ themeConfig }) => {
						return themeConfig.guidebookSectionUnfoldOneImage;
					},
					closeSingle: ({ themeConfig }) => {
						return themeConfig.guidebookSectionFoldOneImage;
					},
					drawerFolderImage: ({ themeConfig }) => {
						return themeConfig.drawerFolderImage;
					}
				})
			},
			watch: {
				'connRecordList': function(newVal, oldVal) {
					if(newVal.length == 0) {
						// 关闭页面
						this.closeWindowModal = true;
						setTimeout(() => {
							window.close();
						}, 1000);
						return
					}
					let newrecord = newVal[0];
					let oldrecord = oldVal[0];
					this.curVmName = newrecord.name;
					this.curAccess = newrecord.protocol;
					if((newrecord && !oldrecord) || newrecord.id != oldrecord.id) {
						this.recordOpenAct(newrecord.id, newrecord.width, newrecord.height)
					}
				}
			},
			methods: {
				//          ...mapActions('edu', [
				//              'getRecordList' // -> this.getRecordList()
				//          ]),
				// 获取vms
				getVmList() {
					getVms(this.proId).then(data => {
						if(data.code == 1) {
							let vms = data.attribute.vms
							this.vmList = vms;
							if(vms.length > 0) {
								this.curVmName = vms[0].name;

								this.curAccess = vms[0].accesses[0].accessType;
							} else {
								this.$Message.error('该工程已被删除或正在重新部署');
							}
						} else {
							this.$Message.error(data.message)
						}
					})
				},
				// 获取销毁时间
				getDestoryTime() {
					getTime(this.proId)
						.then(data => {
							if(data.code === 1) {
								this.leftTime = data.attribute.destroyTime;
								if(this.leftTime > 0) {
									this.getTimes();
								} else {
									window.close();
								}
							}
						})
						.catch(err => {
							console.log(err)
						})
				},
				getTimes() {
					clearTimeout(this.timeout);
					let leftTime = this.leftTime;
					if(leftTime > 0) {
						let h = Math.floor(leftTime / 1000 / 60 / 60);
						let m = Math.floor(leftTime / 1000 / 60 % 60);
						let s = Math.floor(leftTime / 1000 % 60);
						this.curTime = {
							h: h < 10 ? '0' + h : h,
							m: m < 10 ? '0' + m : m,
							s: s < 10 ? '0' + s : s
						}
						let _this = this;
						this.timeout = setTimeout(() => {
							_this.leftTime = _this.leftTime - 1000;
							_this.getTimes();
						}, 1000);
					} else {
						// 关闭页面
						this.closeWindowModal = true;
						this.timeout = setTimeout(() => {
							this.closeTime = this.closeTime - 1;
							if(this.closeTime <= 0) {
								window.close();
							}
							this.getTimes();
						}, 1000);
					}
				},
				// 左侧信息栏
				clickMenu(index) {
					for(let i = 0; i < this.leftMenu.length; i++) {
						this.leftMenu[i].type = false
					}
					this.leftMenu[index].type = true
				},
				closeLeft() {
					if(this.contrlStatus) {
						this.contrlImg = require('../../../assets/exper/open-book.png')
						this.leftContentWidth = '0px'
						$('.left-content').css({
							padding: '0',
						})
						$('.left-menu').css({
							display: 'none'
						})
					} else {
						this.contrlImg = require('../../../assets/exper/close-book.png')
						this.leftContentWidth = '650px'
						$('.left-content').css({
							padding: '20px 0 20px 20px'
						})
						$('.left-menu').css({
							display: 'flex'
						})
					}
					this.contrlStatus = !this.contrlStatus
					this.getVmsWidth()
				},
				// 试验机宽度
				getVmsWidth() {
					let leftWidth = parseInt(this.leftContentWidth.split('px')[0]) // + 60
					$('#content').css({
						width: this.fullWidth - leftWidth + 'px'
					})
				},
				// 获取课件详情
				getExperData() {
					let params = {
						eid: this.ecId,
						uid: this.USER_ID,
					}
					experimentDetail(params)
						.then(data => {
							if(data.code === 1) {
								//let getData = data.attribute.data
								// 课件信息
								this.expeInfo = data.data;
                if(this.expeInfo.customType==1){
                      this.guideSrc = `/api/minio/filePreview?path=${this.expeInfo.guide}`;
                  }else{
                    // 指导书
                    this.getGuideFun();
                  }
							} else {
								this.$Message.error({
									content: data.message,
									duration: 3,
								})
							}
						})
						.catch(err => {
							console.log(err)
						})
				},
				// 课件指导书信息
				getGuideFun() {
					let _this = this
					let params = {
						id: this.expeInfo.guide
					}
					sectionList_new(this.ecId, this.expeInfo.guide)
						.then(data => {
							if(data.code === 1) {
								this.guideList = data.attribute.datalist
							} else {
								this.$Message.error(data.message)
							}
						})
						.catch(err => {
							this.$Message.error(err.data.message)
							console.log(err)
						})
					},
				// 获取实时推送的画面
				recordOpenAct(uToken, width, height, vmName, userName, type, loginTime) {
					$("#mainIframe").empty()
					$("#mainIframe").show();
					if(uToken) {
						let webRecordId = uToken;
						let vncWidth = $("#content").outerWidth();
						let vncHeight = $("#content").outerHeight();

						let scaleW = vncHeight / height;
						let display = document.getElementById("mainIframe");
						let tunnel;
						let loc = window.location,
							web_url;
						if(loc.protocol === "https:") {
							web_url = "wss:"
						} else {
							web_url = "ws:";
						}
						web_url += "//" + loc.host;
						web_url += "/api/access/tunnel/webSocket";
						if(!!window.WebSocket && window.WebSocket.prototype.send)
							tunnel = new Guacamole.WebSocketTunnel(web_url);
						else {
							alert('非常抱歉，您的浏览器不支持WebSocket，请安装最新谷歌浏览器再试。')
						}
						var guac = new Guacamole.Client(
							tunnel
						);
						display.appendChild(guac.getDisplay().getElement());
						guac.getDisplay().scale(scaleW);
						guac.onerror = function(error) {
							console.log(error);
						};
						// Connect
						var paramStr = 'sessionId=' + webRecordId +
							'&width=' + vncWidth +
							'&height=' + vncHeight + '&observer=true';
						guac.connect(paramStr);
						//this.modifyCheckScreenStatus(1);
					} else {
						$("#mainIframe").append('<div class="unconnectVNC">当前无实时接入</div>')
					}

				},
				//记录查看投屏状态
				modifyCheckScreenStatus(status) {
					let params = {
						classId: this.$route.query.classId,
						classNumberId: this.$route.query.classNumberId,
						ecId: this.$route.query.courseId,
						isGetScreen: status
					}
					modifyCheckScreenStatus(params).then(data => {
						if(data.code == 1) {

						} else {
							this.$Message.error({
								content: data.message,
								duration: 3,
							})
						}
					})
				},
				getRecordList(params) {
					getRecord(params).then(data => {
						if(data.code == 1) {
							this.connRecordList = data.data.items;
						} else {
							this.connRecordList = [];
						}
					})
				},
				escape2Html(str) {
					return escape2Html(str);
				}
			}
	}
</script>

<style scoped>
	.ivu-layout-content {
		height: calc( 100vh - 60px);
	}
	
	.ivu-layout-header {
		height: 60px;
		line-height: 60px;
		margin-bottom: 3px;
		background: #fff;
		color: #000;
		overflow: hidden;
		box-shadow: 0 0px 5px 1px #515a6e;
	}
	
	.ivu-drawer-header {
		display: none;
	}
	
	.ivu-drawer {
		top: 63px!important;
	}
	
	.operation {
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}
	
	.operation>li {
		margin-left: 30px;
	}
	
	#childMenu .ivu-select-dropdown {
		width: 100px;
	}
	
	.environWrapper {
		width: 100%;
		height: 100%;
		overflow: hidden;
	}
	
	.environWrapper .ivu-dropdown-item {
		padding: 7px 10px;
	}
	
	.environWrapper .ivu-layout-header {
		padding: 0 20px 0 20px;
	}
	
	#content {
		height: 100%;
		transition: width 1s;
	}
	/*新样式*/
	
	.left-wrap {
		height: 100%;
		display: flex;
		justify-content: flex-start;
		background-color: #fff;
		position: relative;
		transition: width 1s;
	}
	
	.left-menu {
		width: 60px;
		display: flex;
		justify-content: space-between;
		transition: width 1s;
	}
	
	.left-items {
		display: flex;
		justify-content: flex-start;
		flex-direction: column;
		padding-top: 30px;
		width: 58px;
	}
	
	.left-item {
		padding-left: 15px;
		margin-bottom: 30px;
		cursor: pointer;
	}
	
	.left-item:after {
		display: block;
		content: '';
		clear: both;
	}
	
	.item-text {
		writing-mode: vertical-lr;
		color: #333;
		font-weight: 600;
		display: inline-block;
	}
	
	.textActive {
		color: #2f70ff;
	}
	
	.item-line {
		width: 4px;
		border-radius: 2px;
		height: 25px;
		background-color: #fff;
		float: right;
	}
	
	.lineActive {
		background-color: #2f70ff;
	}
	
	.left-content {
		padding: 20px 0 20px 20px;
		transition: width 1s;
	}
	
	.contrlIcon {
		position: absolute;
		top: 130px;
		right: -17px;
		cursor: pointer;
		z-index: 10;
		opacity: 0.5;
	}
	
	.exap-data-wrap {
		width: 100%;
		overflow-x: hidden;
		overflow-y: auto;
	}
	
	.exap-data {}
	
	.main_list {
		width: 98%;
		overflow: hidden;
	}
	
	.main_list .exp {
		width: 100%;
		overflow: hidden;
		display: none;
	}
	
	.main_list .exp .guidancebook {
		overflow: hidden;
		/*margin: 30px 0 0 33px;*/
		position: relative;
		min-height: 98px;
	}
</style>